<script setup lang="ts">
import { nextTick, onMounted, reactive } from 'vue'

import NavSide from '../components/wechat/NavSide.vue'
import ChatMenu from '../components/wechat/ChatMenu.vue'
import MainTop from '../components/wechat/MainTop.vue'
import MainBottom from '../components/wechat/MainBottom.vue'
import ChatBox from '../components/wechat/ChatBox.vue'

import { base64ToBlob, mimeTypes, checkBlobUrlValidity } from '../utils/blob'
import { deepClone } from '../utils/json'
import { merge } from 'lodash-es'
import dayjs from 'dayjs'

const wechat = reactive({
    host: '',
    avatar: '',
    menus: [] as ChatMenu[],
    active: {} as ChatMenu,
    collections: [] as Collection[],
    webviewHome: '',
    alwaysOnTop: false,
    borderRadius: false
})

const handleQuit = () => {
    try {
        window.ipcRenderer.send('set-config', {
            wechat: {
                activeIndex: wechat.active?.id || '',
                menus: deepClone(wechat.menus)
            }
        })
    } catch (err) {
        console.error(err)
    }
    window.ipcRenderer.send('close-all-windows')
}

const handleChooseAvatar = async (avatar: any) => {
    await nextTick()
    wechat.avatar = avatar.blobUrl
    window.ipcRenderer.send('set-config', { wechat: { avatar: avatar.path } })
}

const handleActive = (data: ChatMenu) => {
    if (wechat.active && wechat.active.id) {
        const index = wechat.menus.findIndex(item => item.id === wechat.active.id)
        wechat.menus[index] = wechat.active
    }

    wechat.active = data

    const element = document.body.querySelector('.chat-box .el-scrollbar__wrap') as HTMLElement
    if (element) {
        element.scrollTop = element.scrollHeight
    }
}

const handleClear = () => {
    wechat.active.chats = []
    const index = wechat.menus.findIndex(item => item.id === wechat.active.id)
    wechat.menus[index] = wechat.active
}

const handleSend = (data: any) => {
    if (!wechat.active.chats) wechat.active.chats = []
    const chats = wechat.active.chats
    data.isLongTime = true
    if (data.speaker) {
        data.position = 'left'
    } else {
        data.position = 'right'
    }
    if (chats.length > 0) {
        if (dayjs().diff(dayjs(chats[chats.length - 1].time), 'minute') > 2) {
            data.isLongTime = true
        } else {
            data.isLongTime = false
        }
    } else {
        data.isLongTime = true
    }
    data.id = window.electronIpc.randomUUID()
    data.time = dayjs().format('YYYY-MM-DD HH:mm:ss')
    wechat.active.chats.push(data)
}

const toggleAds = () => {
    const webview = document.querySelector('webview') as HTMLWebViewElement
    if (webview) {
        window.F.hidden = !window.F.hidden
        webview.executeJavaScript(`
            document.querySelectorAll('video').forEach(video => ${window.F.hidden ? 'video.pause()' : 'video.play()'})
        `, true)
    }
}

onMounted(async () => {
    let config = await window.ipcRenderer.invoke('read-config'),
        wx = config.wechat
    wechat.host = config.source
    wechat.webviewHome = config.home
    wechat.alwaysOnTop = config.alwaysOnTop
    wechat.borderRadius = config.borderRadius
    wechat.collections = config.menus || []
    if (wx.avatar && !/^https?:\/\//.test(wx.avatar)) {
        let file = await window.ipcRenderer.invoke('load-local-file', wx.avatar)
        let blob = base64ToBlob(file.base64, mimeTypes(file.ext))
        wx.avatar = URL.createObjectURL(blob)
    } else {
        wx.avatar = 'https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png'
    }
    if (wx.menus && wx.menus.length > 0) {
        let effectiveBlob = false
        for (let i = 0; i < wx.menus.length; i++) {
            if (wx.menus[i].type !== 0) continue
            if (/^https?:\/\//.test(wx.menus[i].image)) continue
            if (wx.menus[i].imageBlobUrl) {
                if (!effectiveBlob) effectiveBlob = await checkBlobUrlValidity(wx.menus[i].imageBlobUrl)
                if (effectiveBlob) continue
            }
            let file = await window.ipcRenderer.invoke('load-local-file', wx.menus[i].image)
            let blob = base64ToBlob(file.base64, mimeTypes(file.ext))
            wx.menus[i].imageBlobUrl = URL.createObjectURL(blob)
            if (wx.activeIndex && wx.activeIndex === wx.menus[i].id) {
                wechat.active = wx.menus[i]
            }
        }
    }
    merge(wechat, wx)

    window.F = {
        visible: true,
        hidden: false,
        toggleAds: toggleAds
    }

    document.addEventListener('keydown', function (event) {
        if (event.key === 'Escape') {
            window.ipcRenderer.send('escape')
        }
    })
})
</script>
<template>
    <el-container class="wechat" :style="{
        'border-radius': wechat.borderRadius ? '8px' : '0px'
    }">
        <nav-side :avatar="wechat.avatar" :menus="wechat.menus" @choose-avatar="handleChooseAvatar" />
        <el-main>
            <el-splitter>
                <el-splitter-panel size="30%" :min="212">
                    <chat-menu :active-id="wechat.active?.id" :menus="wechat.menus" :host="wechat.host"
                        :webview-home="wechat.webviewHome" @active="handleActive" />
                </el-splitter-panel>
                <el-splitter-panel :min="400">
                    <main-top :title="wechat.active?.title" :always-on-top="wechat.alwaysOnTop" close-type="danger"
                        @quit="handleQuit" />
                    <el-splitter :class="{
                        'chat-splitter': !wechat.active?.id
                    }" style="height: calc(100% - 70px);" layout="vertical">
                        <el-splitter-panel v-if="wechat.active?.id" size="70%" :min="315">
                            <chat-box :avatar="wechat.avatar" :webview-home="wechat.webviewHome"
                                :active="wechat.active" />
                        </el-splitter-panel>
                        <el-splitter-panel v-if="wechat.active?.id" :min="150">
                            <main-bottom :active="wechat.active" :collections="wechat.collections" @send="handleSend"
                                @clear="handleClear" />
                        </el-splitter-panel>
                    </el-splitter>
                </el-splitter-panel>
            </el-splitter>
        </el-main>
    </el-container>
</template>
<style lang="scss" scoped>
.wechat {
    margin: 8px;
    height: calc(100vh - 16px);
    outline: 1px solid #909c9f;
    border-radius: 8px;
    box-shadow: 0px 0px 10px rgba(0, 0, 0, .12);
    overflow: hidden;

    :deep(.el-button) {
        border-radius: var(--el-border-radius-base) !important;
    }

    :deep(.el-popper) {
        border-radius: var(--el-border-radius-base) !important;
    }

    :deep(.el-input) {
        .el-input__wrapper {
            box-shadow: none;
            background-color: #eaeaea;
            border-radius: var(--el-border-radius-base) !important;

            &.is-focus {
                box-shadow: 0 0 0 1px #83e0b0;
                background-color: #ffffff;
            }
        }

        .el-input-group__append,
        .el-input-group__prepend {
            border-radius: var(--el-border-radius-base) !important;
        }
    }

    :deep(.el-splitter) {
        .el-splitter-bar__dragger:before {
            background-color: #d5d5d5
        }

        .el-splitter-bar__dragger:hover:before {
            background-color: #d5d5d5
        }

        .el-splitter-bar__dragger-horizontal:before {
            width: 1px;
        }
    }

    .el-main {
        background-color: #ededed;
        padding: 0;

        .chat-splitter {
            background-image: url(../assets/wechat/logo-background.png);
            background-repeat: no-repeat;
            background-position: center;
            background-size: 90px;
        }
    }
}
</style>